package com.translate.web.api.controller;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.NativeWebRequest;

import com.common.util.CopyEntity;
import com.common.util.TheMagicSkillOfBeingInvisible;
import com.response.vo.ResponseModel;
import com.returns.value.ICodeAndData;
import com.translate.web.config.contract.IOSSConfig;
import com.controller.base.AbstractCommonController;
import com.jwt.IJwtUtil;
import com.msg.ResponseCode;
import com.translate.entity.CommissionManagement;
import com.translate.entity.Team;
import com.translate.entity.User;
import com.translate.web.param.UpdateEmailParam;
import com.translate.web.param.UpdatePasswordParam;
import com.translate.web.param.UpdateUserByManager;
import com.translate.web.param.UserSearchByDepartmentParam;
import com.param.impl.IdGenericity;
import com.translate.web.service.ICommissionManagementService;
import com.translate.web.service.ITeamService;
import com.translate.web.service.IUserService;
import com.basic.service.contract.IBaseService;
import com.translate.vo.UserByDepartVO;
import com.translate.vo.UserVO;
import com.translate.vo.contract.IUserVO;

@RestController()
@RequestMapping("center")
public class UserCenterController extends AbstractCommonController<User, UserSearchByDepartmentParam>{

    private IUserService userService;

    private IOSSConfig iossConfig;
    
  
    private ITeamService teamService;
    
    IJwtUtil jwtUtil;
    
    ICommissionManagementService commissionManagementService;
    
    @Resource
    public void setCommissionManagementService(ICommissionManagementService commissionManagementService) {
		this.commissionManagementService = commissionManagementService;
	}

	@Resource
    public void setJwtUtil(IJwtUtil jwtUtil) {
		this.jwtUtil = jwtUtil;
	}

	public UserCenterController(IUserService userService) {
        this.userService = userService;
    }

    @Override
	protected IBaseService<User> getBaseService() {
		// TODO Auto-generated method stub
		return this.userService;
	}
    

	private  ResponseModel<IUserVO> getCommonUser(int userId) {
    	
    	IUserVO userVo = this.userService.getUserDetails(userId, UserVO.class); 
    	
    	return ResponseModel.<IUserVO>success(userVo);
    }
    
    @PostMapping("getContractsInfo")
	public ResponseModel<IUserVO> getContractsInfo(@RequestBody @Validated IdGenericity<Long> idGenericityArray) {
		
		int userId = (int) TheMagicSkillOfBeingInvisible.GetDecodeUserID(idGenericityArray.getId());
    	
		return getCommonUser(userId);
	}
    
    @PostMapping("checkOrigialEmail")
    public ResponseModel<Integer> checkOrigialEmail(@RequestBody @Validated UpdateEmailParam param,
    		NativeWebRequest httpServletRequest) {
    	
    	param.setUserId((int) this.getUserId(httpServletRequest));
    	
    	ICodeAndData<Integer> updateEmail = userService.checkEmail(param);
    	
    	int status = updateEmail.getStatus();
    	
    	if (500 == status) {
            return ResponseModel.<Integer>errorMsg(0, updateEmail.getMsg());
        }	
    	
    	return ResponseModel.<Integer>success(status);
    }
    
    
    @PostMapping("updateEmail")
    public ResponseModel<Integer> updateEmail(
    		@RequestBody @Validated UpdateEmailParam param,
    		NativeWebRequest httpServletRequest
    ) {
    	
    	long userId = this.getUserId(httpServletRequest);
    	
    	param.setUserId((int) userId);
    	
    	int status = 0;
    	try {
	    	ICodeAndData<Integer> updateEmail = userService.updateEmail(param);
	    	
	    	status = updateEmail.getStatus();
	    	
	    	if (500 == status) {
	            return ResponseModel.<Integer>errorMsg(0, updateEmail.getMsg());
	        }	
    	} catch (Exception e) {
    		ResponseModel.<Integer>errorMsg(0, "邮箱已注册");
		}
    	
    	return ResponseModel.<Integer>success(status);
    }
    
    protected <VO> Class<VO> getTarget() {
		return (Class<VO>) UserByDepartVO.class;
	}
    

	@PostMapping("getUserDetail")
    public ResponseModel<IUserVO> getUserDetail(NativeWebRequest httpServletRequest) {
    	
    	int userId = (int)this.getUserId(httpServletRequest);
    	
    	IUserVO userVo = this.userService.getUserDetails(userId, UserVO.class); 
    	
    	Integer teamId = userVo.getTeamId();
    	
    	if (null == userVo.getId()) {
    		
            return ResponseModel.<IUserVO>errorMsg(null, ResponseCode.ERROR_LOGIN_FAILURE);
    	}
    	
    	if (0 == teamId) {
    		return ResponseModel.<IUserVO>success(userVo);
    	}
    	
    	if (1 == userVo.getStatus()) {
    		Team selectByPrimaryKey = this.teamService.selectByPrimaryKey(teamId);
    		
    		userVo.setTeamDiscount(selectByPrimaryKey.getDiscount());
        	
        	userVo.setTeamName(selectByPrimaryKey.getGroupName());
    	} else {
    		userVo.setTeamId(0);
    	}
    	
    	
    	
    	return ResponseModel.<IUserVO>success(userVo);
    }
    
	@PostMapping("updateUser")
	@Transactional
    public ResponseModel<Integer> updateUser(
    		@Validated @RequestBody 
    		UpdateUserByManager updateUserParam,  
    		NativeWebRequest httpServletRequest
    ) {
    	
    	User user = CopyEntity.copyEntity(updateUserParam, User.class);
    	
    	long userId = this.getUserId(httpServletRequest);
		user.setId(userId);
    	
    	String avatar = updateUserParam.getAvatar();
    	
    	if (null != avatar) {
    		String prefix = iossConfig.getLocalPicURL();
    		
    		user.setAvatar(avatar.substring(prefix.length()));
    	}
    	
    	userService.cleanCurrentUserCache(userId);
    	
    	Long recommendeduserId = updateUserParam.getRecommendedUserId();
    	
    	if (null == recommendeduserId) {
    		int updateByPrimaryKeySelective = this.userService.updateByPrimaryKeySelective(user);
            return ResponseModel.<Integer>success(updateByPrimaryKeySelective);
    	}
    	
    	User selectByPrimaryKey = this.userService.selectByPrimaryKey((int) userId);
    	
    	if (null != selectByPrimaryKey.getRecommendedUserId()) {
    		int updateByPrimaryKeySelective = this.userService.updateByPrimaryKeySelective(user);
            return ResponseModel.<Integer>success(updateByPrimaryKeySelective);
    	}
    	
    	User recommendedUser = this.userService.selectByPrimaryKey(recommendeduserId.intValue());
    	
    	if (null == recommendedUser) {
            return ResponseModel.<Integer>errorMsg(0, "推荐人不存在");
        }
    	
    	int commissonManagent = commissionManagementService.insertRecommendUser(recommendeduserId, recommendedUser.getRealname());
    	
    	this.userService.updateByPrimaryKeySelective(user);
		return  ResponseModel.<Integer>success(commissonManagent);
    }
	
	@PostMapping("updatePassword")
	public ResponseModel<Integer> updatePassword(@Validated @RequestBody 
			UpdatePasswordParam updatePasswordParam, 
			NativeWebRequest httpServletRequest) {
		
		updatePasswordParam.setUserId((int) this.getUserId(httpServletRequest));
		
		
		ICodeAndData<Integer> updatePassword = this.userService.updatePassword(updatePasswordParam);
		
		int status = updatePassword.getStatus();
		
		if (500 == status) {
			return ResponseModel.<Integer>errorMsg(0, updatePassword.getMsg());
		}
		
		return ResponseModel.<Integer>success(status);
	}

	@Resource
	public void setTeamService(ITeamService teamService) {
		this.teamService = teamService;
	}
	
}
